package cs419.magnusmi.trackitcs;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class ASearchActivity extends ActionBarActivity {

    ListView listView;
    ItemGetList iGetList;
    Context k;
    String user;
    String API;
    Button back;
    TextView resultLabel;

    String name;
    String ItemID;
    String serial;
    String accesories;
    String specFeat;
    String OS;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_asearch);

        //define listview for inventory
        listView = (ListView) findViewById(R.id.listView);


        //capture context of activity for use in asynchronous activity
        k = this;

        //session vars
        Intent i = getIntent();
        user = i.getStringExtra("user");
        API = i.getStringExtra("API");

        //query vars
        name = i.getStringExtra("ItemName");
        ItemID = i.getStringExtra("ItemID");
        serial = i.getStringExtra("SerialNum");
        accesories = i.getStringExtra("Accessories");
        specFeat = i.getStringExtra("SpecialFeatures");
        OS = i.getStringExtra("OperatingSystem");


        //set result label
        resultLabel = (TextView) findViewById(R.id.resultLabel);
        resultLabel.setText("Search results");

        //create new async array list to hold item information and execute get task
        iGetList = new ItemGetList();
        iGetList.execute(name, ItemID, serial, accesories, specFeat, OS);

        back = (Button) findViewById(R.id.RetButton1);

        back.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                //Launching add activity
                Intent i = new Intent(getApplicationContext(), Inventory.class);
                Utility.addToIntent(i, user, API);
                startActivity(i);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu)  {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.logout:
                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                //clear stack to enforce logout (http://stackoverflow.com/questions/3007998/on-logout-clear-activity-history-stack-preventing-back-button-from-opening-l)
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                        Intent.FLAG_ACTIVITY_CLEAR_TASK |
                        Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
                return true;
            case R.id.inventory_menu:
                Intent j = new Intent(getApplicationContext(), Inventory.class);
                Utility.addToIntent(j, user, API);
                startActivity(j);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to get item list
     * the user.
     */

    public class ItemGetList extends AsyncTask<String, Void, JSONObject> {

        //array list to store item descriptor strings
        ArrayList<String> items  = new ArrayList<String>();
        //array list to store item IDs (parallels items list; for passing to itemView intents)
        ArrayList<Integer> itemIDs = new ArrayList<Integer>();

        /**
         * Gets inventory from database
         * @param params none
         * @return json object containing database inventory results
         */
        @Override
        protected JSONObject doInBackground(String... params) {

            String name = params[0];
            String ItemID = params[1];
            String Serial = params[2];
            String Accessories = params[3];
            String SpecFeat = params[4];
            String OS = params[5];


            //url of PHP to get list
            String getList = "http://web.engr.oregonstate.edu/~cohenad/cs419/index.php/AdvSearch";

            //pointer to array list on inventory page

            //execute get request for list
            JSONParser jsonParser = new JSONParser();
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("Name", name));
            parameters.add(new BasicNameValuePair("ItemID", ItemID));
            parameters.add(new BasicNameValuePair("SerialNum", Serial));
            parameters.add(new BasicNameValuePair("Accessory", Accessories));
            parameters.add(new BasicNameValuePair("SpecialFeature", SpecFeat));
            parameters.add(new BasicNameValuePair("OperatingSystem", OS));

            JSONObject json = jsonParser.makeHttpRequest(getList, "GET", parameters);
            return json;
        }

        /**
         * Method to add content to listview after getting content online
         * @param json json array containing results of HTTP get
         */
        @Override
        protected void onPostExecute(JSONObject json) {


            //parse JSON array
            try{
                //create list of items to print.  these are saved in json array with identifier "display[index]"
                if (json.getBoolean("error")  == true){
                    items.add(json.getString("message"));
                    Log.d("message", json.getString(("message")));
                }

                else {
                    int length = json.getInt("Length");
                    for (int i = 0; i < length; i++) {
                        items.add(json.getString("display" + i));
                    }
                    //create array of ids to match items for use in clicking links.  These are saved in json array with identifier "id[index]"
                    for (int i = 0; i < length; i++) {
                        itemIDs.add(json.getInt("id" + i));
                    }
                }
                //DEBUG System.out.println("Inventory done 2");
            }
            catch (JSONException e) {
                Log.d("JSONErr", "JSON error");
            }

            // Define a new Adapter
            // First parameter - Context
            // Second parameter - Layout for the row
            // Third parameter - ID of the TextView to which the data is written
            // Fourth - the Array of data (returned from async task)
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(k,
                    android.R.layout.simple_list_item_1, android.R.id.text1, items){
                @Override
                public View getView(int position, View convertView,
                                    ViewGroup parent) {
                    View view =super.getView(position, convertView, parent);

                    TextView textView=(TextView) view.findViewById(android.R.id.text1);

                    /*YOUR CHOICE OF COLOR*/
                    textView.setTextColor(Color.WHITE);

                    return view;
                }
            };

            // Assign adapter to ListView
            listView.setAdapter(adapter);

            // Create click listener for each item
            AdapterView.OnItemClickListener detailListen = new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View v, int position, long ident) {
                    //DEBUG System.out.println("Id is:" + itemIDs.get(position));

                    //on click, bring up item detail view
                    Intent display = new Intent(getApplicationContext(), ItemView.class);
                    String id = itemIDs.get(position).toString();
                    display.putExtra("id", id);
                    Utility.addToIntent(display, user, API);
                    startActivity(display);
                }
            };
            //assign item listener to listview
            listView.setOnItemClickListener(detailListen);
        }
    }
}
